<?php
namespace app\admin\controller;

class Tag extends Admin {
    public function __construct() {
        parent::__construct();
        $this->model = "Tag";
        $this->assign("model", $this->model);
    }

    public function index() {
		$taglist = model($this->model)->select();
		$this->assign('taglist', $taglist);
        return $this->fetch();
    }

    public function get_where_map() {
        $tagname = input("param.tagname", 0);
        $whereDatas = [];
        if ($tagname) {
            $whereDatas['tagname'] = ['like', '%' . $tagname . '%'];
        }
        if ($this->uinfo['roleid'] == 6) {
            $whereDatas['tagdealer'] = $this->uinfo['dealerid'];
        }
        return $whereDatas;
    }

    public function index_tag() {
        $where['status'] = 0;
        if ($this->uinfo['roleid'] == 1) {
            $where['roleid'] = 6;
        } elseif ($this->uinfo['roleid'] == 4) {
            $where['roleid'] = 6;
            $where['puserid'] = $this->uinfo['userid'];
        } elseif ($this->uinfo['roleid'] == 6) {
            $where['userid'] = $this->uinfo['userid'];
        }
        $deallist = model('AdminUser')->where($where)->order('userid desc')->column('userid, username');
        $this->assign('deallist', $deallist);
        return $this->fetch();
    }

    // 管理员添加标签
    public function add_tag() {
        $data = input("post.postData");
        parse_str($data, $tagdata);
        // 标签名字
        if (!isset($tagdata['tagname']) || preg_replace('# #', '', $tagdata['tagname']) == '') {
            return json(['status' => 0, 'msg' => '请输入标签名字']);
        } else {
            $tagdata['tagname'] = trim($tagdata['tagname']);
        }
        // 标签所属经销商
        $roleid = $this->uinfo['roleid'];
        if ($roleid == 1 || $roleid == 4) {
            if (!isset($tagdata['tagdealer']) || $tagdata['tagdealer'] == '') {
                return json(['status' => 0, 'msg' => '请选择所属经销商']);
            }
        } else {
            $tagdata['tagdealer'] = $this->uinfo['dealerid'];
        }
        // 保存数据
        $id = model($this->model)->save_data($tagdata);
        if ($id === false) {
            return json(['status' => 0, 'msg' => model($this->model)->getError()]);
        }
        return json(['status' => 1, 'msg' => '操作成功']);
    }

    // 经纪人列表（可设置标签的用户列表）
    public function tag_user_list() {
        $keywords = input('param.keywords');
        $order = input("param.order/s");
        $page = input("param.page", 1);
        $limit = input("param.limit", $this->default_page_items);
        $isvip = input("param.isvip/s");
        $dealerid = input('param.dealerid/d');
        $startdate = input('param.startdate/s');
        $enddate = input('param.enddate/s');
        $whereDatas = [];
        if ($keywords) {
			$whereDatas['userid|username|fullname|realname|phone'] = ['like', "%$keywords%"];
		}
        if ($this->uinfo['roleid'] == 6) {
            $whereDatas['dealerid'] = $this->uinfo['dealerid'];
        }
        $whereDatas['roleid'] = '9';
        if ($isvip != '') {
            $whereDatas['vip'] = $isvip;
        }
        if ($dealerid) {
            $whereDatas['dealerid'] = $dealerid;
        }
        if ($startdate && $enddate) {
            $whereDatas['vip'] = 1;
            $whereDatas['addtime'] = ['between', [strtotime($startdate), strtotime($enddate)]];
        }
        $db = model('AdminUser');
        $offset = ($page - 1) * $limit;
        list($userlist, $where) = $db->get_list([], $whereDatas, $limit, $offset, $order);
        $count = $db->where($whereDatas)->count();
        $return = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $userlist,
        ];
        return json($return);
    }

    // 为经纪人批量设置标签
    public function choose_tag() {
        $checked_userids = input("param.items");
        $userid = input("param.userid/s");
        $where = [];
        if ($this->uinfo['roleid'] == 6) {
            $where['tagdealer'] = $this->uinfo['dealerid'];
        }
        $list = model('Tag')->where($where)->select();
        $this->assign('lists', $list);
        if ($checked_userids != null) {
            $this->assign('checked_userids', $checked_userids);
            $this->assign('checked_tagids', '');
        } else if($userid != null) {
            $ids = model('UserTag')->where('userid', $userid)->field('tagid')->select();
            $checked_tagids = '';
            foreach ($ids as $value) {
                $checked_tagids = $checked_tagids . $value['tagid'] . ',';
            }
            if ($checked_tagids != '') {
                $checked_tagids = rtrim($checked_tagids, ',');
            }
            trace($checked_tagids);
            $this->assign('checked_userids', $userid);
            $this->assign('checked_tagids', $checked_tagids);
        }
        return $this->fetch();
    }

    // 为每个经纪人设置标签（多对多）
    public function user_tag() {
        $postData = input("post.postData");
        parse_str($postData, $dataarr);
        $user_ids = explode(',', rtrim($dataarr['user_ids'], ','));
        if (!isset($dataarr['check_tags'])) { // 清空用户标签
            model('UserTag')->whereIn('userid', $dataarr['user_ids'])->delete();
            return json(['status' => 1, 'msg' => '操作成功']);
        }
        $tag_ids = $dataarr['check_tags'];
        $data = [];
        foreach ($user_ids as $userid) {
            foreach ($tag_ids as $tagid) {
                $a_data['userid'] = $userid;
                $a_data['tagid'] = $tagid;
                $data[] = $a_data;
                $a_data = [];
            }
        }
        foreach ($data as $key => $value) {
            $tagid = $value['tagid'];
            $tagdealerid = model('Tag')->where('id', $tagid)->value('tagdealer');
            $value['tagdealerid'] = $tagdealerid;
            $data[$key] = $value;
        }
        $roleid = $this->uinfo['roleid'];
        foreach ($data as $value) {
            if ($roleid == '1' || $roleid == '4') {
                model('UserTag')->where('userid', $value['userid'])->delete();
            } else if ($roleid == '6') {
                model('UserTag')->where('userid', $value['userid'])->where('tagdealerid', $value['tagdealerid'])->delete();
            }
        }
        $id = model('UserTag')->save_data($data);
        if ($id === false) {
            return json(['status' => 0, 'msg' => '保存失败']);
        }
        return json(['status' => 1, 'msg' => '操作成功']);
    }

    public function edit_tag() 
    {
        $this->fetch();
    }

    public function append_coupons() 
    {
        $whereDatas = ['auditstatus' => '1'];
		$roleid = $this->uinfo['roleid'];
		$userid = $this->uinfo['userid'];
		$targettagid = input("param.tagid/s");
		if ($roleid == 4) {
			$whereDatas['createrid'] = ['neq', '1'];
		} else if ($roleid !== 1) {
			$whereDatas['createrid'] = $userid;
		}
		//
        $list = model('Coupons')->where($whereDatas)->select();
        foreach ($list as $data) {
			if ($data['type'] == 'activity') {
				$data['type'] = '活动券';
			} else {
				$data['type'] = $data['type'] ? config('COUPONS_TYPE.' . $data['type']) : '未设置';
			}
		}
		$this->assign('lists', $list);
		$this->assign('tagid', $targettagid);
		return $this->fetch();
    }

    // 标签用户
    public function tag_user() 
    {
        $whereDatas = [];
		$roleid = $this->uinfo['roleid'];
		$userid = $this->uinfo['userid'];
        $tagid = input("param.tagid/s");
        $whereDatas['tagid'] = $tagid;
		if ($roleid == 1 || $roleid == 4) {
		} else {
			$whereDatas['tagdealerid'] = $userid;
		}
		//
        $userlist = model('UserTag')->where($whereDatas)->field('userid');
        // foreach ($list as $data) {
		// 	if ($data['type'] == 'activity') {
		// 		$data['type'] = '活动券';
		// 	} else {
		// 		$data['type'] = $data['type'] ? config('COUPONS_TYPE.' . $data['type']) : '未设置';
		// 	}
		// }
		$this->assign('lists', $userlist);
		$this->assign('tagid', $tagid);
		return $this->fetch();
    }

    public function taguserlist() 
    {
        $page = input("param.page", 1);
        $order = input("param.order");
        $tagid = input("param.tagid");
		$limit = input("param.limit", $this->default_page_items);
		$db = model('AdminUser');
		$offset = ($page - 1) * $limit;
        $whereMap = [];
        $useridlist = model('UserTag')->where('tagid', $tagid)->column('userid');
        $whereMap['userid'] = ['in', $useridlist];
        $whereMap['vip'] = 1;
        // $whereMap['tagid'] = $tagid;
		// $check_controller = Request::instance()->controller();
		// if (!isset($whereMap['userid']) && $this->uinfo['roleid'] != 1 && $check_controller != 'Convert') {
		// 	if ($check_controller != 'Lunbo') {
		// 		$whereUserid = [];
		// 		if ($check_controller == 'Memberbouns' && $this->uinfo['roleid'] == '6') {
		// 			$tempids1 = model('AdminUser')->where('dealerid', $this->uinfo['userid'])->where('roleid', '9')->column('userid');
		// 			$tempids2 = $db->where('userid', 'in', $tempids1)->column('userid');
		// 			$whereMap['userid'] = ['in', $tempids2];
		// 		} else {
		// 			$whereMap = $whereUserid ? array_merge($whereMap, $whereUserid) : $whereMap;
		// 		}
		// 		// $whereUserid = $this->get_userids();
		// 	}
		// }
        list($list, $count) = $db->admin_get_list($offset, $limit, $whereMap, $order);
		$return = [
			'code' => 0,
			'msg' => '',
			'count' => $count,
			'data' => $list,
		];
		return json($return);
    }

    // 给某标签补发优惠券
	public function set_coupons()
	{
		$postData = input("post.postData");
        parse_str($postData, $dataarr);
		$couponsid = $dataarr['check_id'];
        $tagid = $dataarr['id'];
		exec_php('/index/cron/send_coupons', ['type' => 'send_taguser_coupons', 'couponsid' => $couponsid, 'tagid' => $tagid]);
        return json(['status' => 1, 'msg' => '操作成功']);
        // $userids = [];
        // if (isset($dataarr['check_userids'])) {
        //     $userids = $dataarr['check_userids'];
        // }
        // if ($couponsid) {
        //     model('CouponsUser')->where('couponsid', $couponsid)->delete();
        // }
        // $data = [];
        // foreach ($userids as $userid) {
        //     $a_data['couponsid'] = $couponsid;
        //     $a_data['userid'] = $userid;
        //     $data[] = $a_data;
        //     $a_data = [];
        // }
        // if ($data) {
        //     $id = model('CouponsUser')->save_data($data);
        //     if ($id === false) {
        //         return json(['status' => 0, 'msg' => '保存失败']);
        //     }
        // }
	}
}
